//
//  TMGSaleGoldViewController.m
//  TMGold
//
//  Created by Mac on 2017/12/12.
//  Copyright © 2017年 tangmu. All rights reserved.
//

#import "TMGBootomGoldBuyViewController.h"
#import "NSCalendar+STCalendarTool.h"
@interface TMGBootomGoldBuyViewController ()
@property(nonatomic, strong) UITextField                     *textFiled;
@property(nonatomic, strong) NSArray                        *dataSouce;
@end

@implementation TMGBootomGoldBuyViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configDataSouce];
    self.title = self.model.name;
    [self configSubView];
    [self configFooterView];
    [self configBottomView];
    [self addNotifacations];
}
#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(uitextFieldTextDidChangeNotification:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
    
}
- (void)uitextFieldTextDidChangeNotification:(NSNotification*)notify{
    
    if (notify.object == self.textFiled) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            CGFloat ke = [self.textFiled.text floatValue];
            CGFloat money = ke * self.model.price.floatValue;
            STTableEasyModel * model = self.dataSouce[1];
            model.detailString = [NSString stringWithFormat:@"%0.2f(元)",money];
            [self.tableView reloadData];
        });
        
    }
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)configDataSouce{
    self.textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 0.66*UIScreenWidth, 44)];
    self.textFiled.placeholder = @"输入购买重量";
    self.textFiled.keyboardType = UIKeyboardTypeDecimalPad;
    NSString * rate = self.model.year_rate_from;
    if (self.model.year_rate_to.floatValue > 0.1) {
        rate = [NSString stringWithFormat:@"%@~%@",self.model.year_rate_from,self.model.year_rate_to];
    }
    rate = [NSString stringWithFormat:@"%@%%",rate];
    
    self.dataSouce = @[
                       [[STTableEasyModel alloc] initWithTextString:@"购买克重" accessoryView:self.textFiled],
                       [[STTableEasyModel alloc] initWithTextString:@"预计金额 " detailString:@"0.00"],
                       [[STTableEasyModel alloc] initWithTextString:@"利率"
                                                       detailString:rate],
                       [[STTableEasyModel alloc] initWithTextString:@"计息日" detailString:[NSDate st_localCurrentDate].st_yyyyMMddByLineWithDate]];
    [self.tableView reloadData];
}
#pragma mark --subView
- (void)configSubView{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 100)];
    header.backgroundColor = [UIColor whiteColor];
    
    UIImageView * bannerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 193)];
    bannerImageView.image = [UIImage imageNamed:@"wdebanner"];
    bannerImageView.userInteractionEnabled = YES;
    [header addSubview:bannerImageView];
    
    
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, 10, 200, 80)
                                                     text:[NSString stringWithFormat:@"%@\n实时金价(元/克)",
                                                           self.model.price]
                                                textColor:[UIColor whiteColor]
                                                     font:26
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentCenter];
    titleLable.centerX = UIScreenWidth / 2;
    titleLable.attributedText = [titleLable.text st_convertAttributeStringWithKeyWord:@"实时金价(元/克)" attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]}];
    [bannerImageView addSubview:titleLable];
    
    STLabel * saleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, bannerImageView.bottom, UIScreenWidth, 60)
                                                    text:@"账户余额0.00元"
                                               textColor:TM_firstTextColor
                                                    font:15
                                             isSizetoFit:NO
                                           textAlignment:NSTextAlignmentCenter];
    saleLable.backgroundColor = [UIColor whiteColor];
    [header addSubview:saleLable];
    
    
    [TMUtils fetchPersonnalInfo:^(TMGUserModel *user) {
        saleLable.text = [NSString stringWithFormat:@"账户余额%@元",user.money];
        saleLable.attributedText = [saleLable.text st_convertAttributeStringWithKeyWord:user.money attributes:@{NSForegroundColorAttributeName:TM_orangeColor}];
    }];
    header.height = saleLable.bottom;
    //头部橘色
    UIView * headers = [[UIView alloc] initWithFrame:CGRectMake(0, -header.height, UIScreenWidth, 2 * header.height)];
    headers.backgroundColor = TM_orangeColor;
    [header insertSubview:headers atIndex:0];
    
    self.tableView.tableHeaderView = header;
    
}
- (void)configBottomView{
    
    
    __weak typeof(self) weakSelf =  self;
    STButton * nextButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth / 1, 49)
                                                      title:@"确定下单"
                                                 titleColor:FlatWhite
                                                  titleFont:15
                                               cornerRadius:0
                                            backgroundColor:TM_orangeColor
                                            backgroundImage:nil
                                                      image:nil];
    nextButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [nextButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedNextButton];
    }];
    nextButton.top = [TMUtils tabBarTop];
    [self.view addSubview:nextButton];
    
    
    STButton * desButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, UIScreenHeight, 44)
                                                     title:@"我已经认真阅读并同意流动金-黄金消费综合服务项目"
                                                titleColor:TM_secendTextColor
                                                 titleFont:13
                                              cornerRadius:0
                                           backgroundColor:self.tableView.backgroundColor
                                           backgroundImage:nil
                                                     image:[UIImage imageNamed:@"yi_xuanzhong"]];
    desButton.imageEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 0);
    desButton.titleEdgeInsets = UIEdgeInsetsMake(0, 25, 0, 0);
    [desButton setAttributedTitle:[desButton.currentTitle st_convertAttributeStringWithKeyWord:@"流动金-黄金消费综合服务项目" attributes:@{NSForegroundColorAttributeName:TM_orangeColor}] forState:UIControlStateNormal];
    desButton.bottom = nextButton.top;
    [self.view addSubview:desButton];
    
}
- (void)configFooterView{
    __weak typeof(self) weakSelf =  self;
    UIView * footer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 44)];
    footer.backgroundColor = self.tableView.backgroundColor;
    STButton * confimButton = [[STButton alloc] initWithFrame:CGRectMake(15, 0, UIScreenWidth - 30 , 44)
                                                        title:@"投资小提示 点击查看"
                                                   titleColor:TM_firstTextColor
                                                    titleFont:14
                                                 cornerRadius:10
                                              backgroundColor:nil
                                              backgroundImage:nil
                                                        image:nil];
    [confimButton setAttributedTitle:[confimButton.currentTitle st_convertAttributeStringWithKeyWord:@"点击查看" attributes:@{NSForegroundColorAttributeName:TM_orangeColor}] forState:UIControlStateNormal];
    
    [confimButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelectedAlertButton];
    }];
    confimButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [footer addSubview:confimButton];
    self.tableView.tableFooterView = footer;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count ;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 44;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuseIdentifier];
        
    }
    cell.textLabel.textColor = UIColorFromRGBA(0x333333);
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.detailTextLabel.font = [UIFont systemFontOfSize:13];
    cell.detailTextLabel.textColor = [UIColor blackColor];
    
    STTableEasyModel * model = self.dataSouce[indexPath.row];
    cell.textLabel.text = model.textString;
    cell.accessoryType = UITableViewCellAccessoryNone;
    if (model.accessoryView) {
        cell.accessoryView = model.accessoryView;
    }else{
        cell.detailTextLabel.text = model.detailString;
    }
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --Action Method
- (void)onSelectedAlertButton{
    
}
//确定下单
- (void)onSelectedNextButton{
    CGFloat money = self.textFiled.text.floatValue * self.model.price.floatValue;
    if (money < 1) {
        [SVProgressHUD showErrorWithStatus:@"您还没选择重量哦"];
        return;
    }
    [self sendBuyRequest];
//    NSString * title = [NSString stringWithFormat:@"您一共选择了%@克一共%0.2f元",self.textFiled.text,money];
//    
//    [self showAlertWithTitle:title
//                  titleColor:FlatBlack
//                     message:@"请问确定购买吗？"
//                messageColor:FirstTextColor
//                   leftTitle:@"取消"
//              leftTitleColor:SecendTextColor
//                  rightTitle:@"确认"
//             rightTitleColor:TM_orangeColor
//                      handle:^(NSString *name) {
//                          
//                          if ([name isEqualToString:@"确认"]) {
//                              [self sendBuyRequest];
//                          }
//                      }];
}
#pragma mark --NetWork Method
- (void)sendBuyRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",service_header,@"/gold/public/api/order/addOrderBuy"];
    if ([STUserManger defult].userID.length) {
        [dic setObject:[STUserManger defult].userID forKey:@"uid"];
    }
    if ([STUserManger defult].token.length) {
        [dic setObject:[STUserManger defult].token forKey:@"token"];
    }
    [dic setObject:self.model.goodID forKey:@"gid"];
    [dic setObject:@"1" forKey:@"cate"];
    [dic setObject:self.model.year_rate_from forKey:@"year_rate"];
    [dic setObject:@"1" forKey:@"trade_type"];
    NSDate * date = [NSDate st_localCurrentDate];
    NSString * today = date.st_yyyyMMddByLineWithDate;
    [dic setObject:today forKey:@"start"];
    for (NSInteger i =0; i < 90; i ++ ) {
        date = [NSCalendar st_nextDayDate:date];
    }
    if (self.textFiled.text.length) {
        [dic setObject:self.textFiled.text forKey:@"goods_number"];
    }
    NSString * end = date.st_yyyyMMddByLineWithDate;
    [dic setObject:end forKey:@"end"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"购买成功"];
                                                 [self.navigationController popViewControllerAnimated:YES];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end

